package com.treetao.union.web.controller.mall;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.treetao.union.db.model.MallPAttr;
import com.treetao.union.db.model.MallPAttrItem;
import com.treetao.union.db.model.MallPSkuAttrItem;
import com.treetao.union.db.model.vo.LayerData;
import com.treetao.union.db.model.vo.RestResponse;
import com.treetao.union.db.service.MallPAttrItemService;
import com.treetao.union.db.service.MallPAttrService;
import com.treetao.union.db.service.MallPSkuAttrItemService;
import com.treetao.union.web.constant.Constants;
import com.treetao.union.web.controller.BaseController;
import com.treetao.union.web.pojo.XmSelectPojo;

/**
 * <p>
 * 商品属性 前端控制器
 * </p>
 *
 * @author Dev.M
 * @since 2020-04-11
 */
@Controller
@RequestMapping(Constants.AMIND_PREFIX + "/mall-pattr")
public class MallPAttrController extends BaseController {

	@Autowired
	private MallPAttrService mallPAttrService;

	@Autowired
	private MallPAttrItemService mallPAttrItemService;
	
	@Autowired
	private MallPSkuAttrItemService mallPSkuAttrItemService;

	@GetMapping("list")
	public String list() {
		return "/admin/mall-pattr/list";
	}

	@PostMapping("list")
	@ResponseBody
	public LayerData<MallPAttr> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "limit", defaultValue = "10") Integer limit, ServletRequest request) {
		Map map = WebUtils.getParametersStartingWith(request, "s_");
		LayerData<MallPAttr> layerData = new LayerData<>();
		QueryWrapper<MallPAttr> wrapper = new QueryWrapper<MallPAttr>();
		if (!map.isEmpty()) {
			String delFlag = (String) map.get("delFlag");
			if (StringUtils.isNotBlank(delFlag)) {
				wrapper.eq("del_flag", Boolean.valueOf(delFlag));
			} else {
				map.remove("del_flag");
			}
			String name = (String) map.get("name");
			if (StringUtils.isNotBlank(name)) {
				wrapper.like("name", name);
			} else {
				map.remove("name");
			}

		}
		IPage<MallPAttr> pageData = mallPAttrService.page(new Page<>(page, limit), wrapper);
		layerData.setData(pageData.getRecords());
		layerData.setCount(pageData.getTotal());
		return layerData;
	}

	@GetMapping("xmSelectData")
	@ResponseBody
	public List<XmSelectPojo> xmSelectData(HttpServletRequest req) {
		Long skuId = null;
		if(req.getParameter("skuId")!=null) {
			skuId =Long.valueOf(req.getParameter("skuId"));
		}
		List<MallPSkuAttrItem> attrItems = mallPSkuAttrItemService.getSkuAttrItems(skuId);
		
		List<XmSelectPojo> result = new ArrayList<XmSelectPojo>();
		QueryWrapper<MallPAttr> wrapper = getQueryWrapperNoDel();
		List<MallPAttr> attrs = mallPAttrService.list(wrapper);
		if(attrs!=null) {
			attrs.forEach(attr -> {
				XmSelectPojo xsp = new XmSelectPojo();
				xsp.setName(attr.getName());
				xsp.setValue(attr.getId());
				
				List<MallPAttrItem> items = mallPAttrItemService.getAttrItems(attr.getId());
				if(items!=null) {
					List<XmSelectPojo> listItems = new ArrayList<XmSelectPojo>();
					items.forEach(item -> {
						XmSelectPojo xsp2 = new XmSelectPojo();
						xsp2.setName(item.getName());
						xsp2.setValue(item.getId());
						xsp2.setDisabled(item.getDelFlag());
						
						if(attrItems!=null) {
							attrItems.forEach(selectedItems -> {
								if(selectedItems.getRefAttrItemId().longValue() == item.getId()) {
									xsp2.setSelected(true);//选中状态
								}
							});
						}
						
						listItems.add(xsp2);
					});
					xsp.setChildren(listItems);
				}
				result.add(xsp);
			});
		}
		return result;
	}

	@GetMapping("add")
	public String add(HttpServletRequest req,Model model) {
		Map<String, String[]> params = req.getParameterMap();
    	for(String key : params.keySet()) {
    		model.addAttribute(key,params.get(key)==null?null:params.get(key)[0]);
    	}
		return "/admin/mall-pattr/add";
	}

	@PostMapping("add")
	@ResponseBody
	public RestResponse add(MallPAttr mallPAttr) {
		if (StringUtils.isBlank(mallPAttr.getName())) {
			return RestResponse.failure("名称不能为空");
		}
		mallPAttrService.save(mallPAttr);
		return RestResponse.success();
	}

	@GetMapping("detail")
	public String detail(Long id, Model model) {
		MallPAttr mallPAttr = mallPAttrService.getById(id);
		model.addAttribute("mallPAttr", mallPAttr);
		return "/admin/mall-pattr/detail";
	}

	@GetMapping("edit")
	public String edit(Long id, Model model) {
		MallPAttr mallPAttr = mallPAttrService.getById(id);
		model.addAttribute("mallPAttr", mallPAttr);
		return "/admin/mall-pattr/edit";
	}

	@PostMapping("edit")
	@ResponseBody
	public RestResponse edit(MallPAttr mallPAttr) {
		if (null == mallPAttr.getId() || 0 == mallPAttr.getId()) {
			return RestResponse.failure("ID不能为空");
		}
		if (StringUtils.isBlank(mallPAttr.getName())) {
			return RestResponse.failure("名称不能为空");
		}
		mallPAttrService.updateById(mallPAttr);
		return RestResponse.success();
	}

	@PostMapping("batchDel")
	@ResponseBody
	public RestResponse batchDel(@RequestParam(value = "ids[]", required = false) List<Long> ids) {
		if (null == ids || ids.size() == 0) {
			return RestResponse.failure("请选择一项");
		}
		return RestResponse.success().setDataOnlyResult(mallPAttrService.removeByIds(ids));
	}

	@PostMapping("delete")
	@ResponseBody
	public RestResponse delete(@RequestParam(value = "id", required = false) Long id) {
		if (null == id || 0 == id) {
			return RestResponse.failure("ID不能为空");
		}
		return RestResponse.success().setDataOnlyResult(mallPAttrService.removeById(id));
	}

	@PostMapping("change-status")
	@ResponseBody
	public RestResponse change_status(@RequestParam(value = "id", required = true) Long id,
			@RequestParam(value = "status", required = false) Boolean status) {
		MallPAttr mallPAttr = mallPAttrService.getById(id);
		mallPAttr.setDelFlag(status);
		mallPAttrService.updateById(mallPAttr);
		return RestResponse.success();
	}

}